<!DOCTYPE html>
<html>
<!--一个文件上传-->
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<input type="file" id="fileInput" />
<button onclick="uploadFile()">上传</button>
<br/><br/>
<input type="text" id="fileNameInput" placeholder="输入要下载或预览的文件名" />
<button onclick="downloadFile()">下载到本地</button>
<button onclick="previewFile()">页面预览</button>
<br/>
<div id="previewArea" style="margin-top:20px; width:600px; height:400px; border:1px solid #ccc;"></div>

<script>
    function uploadFile() {
        var fileInput = document.getElementById('fileInput');
        var file = fileInput.files[0];
        if (!file) {
            alert('请选择一个文件');
            return;
        }
        var formData = new FormData();
        formData.append('file', file);

        axios.post('http://127.0.0.1:8004/file/one', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(function(response) {
            alert('文件上传成功！');
        }).catch(function(error) {
            alert('文件上传失败！');
        });
    }
</script>
<script>
    function downloadFile() {
        var fileName = document.getElementById('fileNameInput').value;
        if (!fileName) {
            alert('请输入文件名');
            return;
        }
        var url = 'http://127.0.0.1:8004/file/download?fileName=' + encodeURIComponent(fileName);
        var a = document.createElement('a');
        a.href = url;
        a.download = fileName;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
    }
    function previewFile() {
        var fileName = document.getElementById('fileNameInput').value;
        if (!fileName) {
            alert('请输入文件名');
            return;
        }
        var url = 'http://127.0.0.1:8004/file/preview?fileName=' + encodeURIComponent(fileName);
        var previewArea = document.getElementById('previewArea');
        // 判断文件类型，图片用img，其它用iframe
        var ext = fileName.split('.').pop().toLowerCase();
        if (["jpg", "jpeg", "png", "gif", "bmp", "webp"].includes(ext)) {
            previewArea.innerHTML = '<img src="' + url + '" style="max-width:100%;max-height:100%;" />';
        } else {
            previewArea.innerHTML = '<iframe src="' + url + '" width="100%" height="100%" frameborder="0"></iframe>';
        }
    }
</script>
</body>
</html>
